//
//  PhotoBrowserCell.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/20.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

//定义协议
protocol PhotoBrowserCellDelegate: NSObjectProtocol {

    //协议实现的方法
    func photoBrowserCellDidTapImage()
    
    //通知代理缩放的比例
    func photoBrowserCellDidZoom(scale: CGFloat)

}

class PhotoBrowserCell: UICollectionViewCell {
    
    //定义代理
    weak var photoDelegate: PhotoBrowserCellDelegate?
    
    //MARK: - 监听方法
    @objc private func tapImage() {
    
        photoDelegate?.photoBrowserCellDidTapImage()
    
    }
    
    
    //定义URL
    var imageURL: NSURL? {
    
        didSet{
        
            guard let url = imageURL else {
            
                return
            }
        
            //重置大小
            resetScrollView()
            
            //1. url的缩略图的地址
            let placeHoderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString)
            
            //2.设置占位图片
            setPlaceHodle(placeHoderImage)
            
            
            //4.异步加载大图
            imageView.sd_setImageWithURL(bmiddleURL(url),
                placeholderImage: nil,
                options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached],
                progress: { (current, total) -> Void in
                    
                    //主线程异步下载
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        
                        self.placeHodle.progress = CGFloat(current) / CGFloat(total)
                    })
                    
                    
                }) { (image, _, _, _) -> Void in
                    
                    //判断图片是否下载成功
                    if image == nil {
                    
                        SVProgressHUD.showInfoWithStatus("您的网速不给力")
                        
                        return
                    
                    }
                    
                    // 隐藏占位图像
                    self.placeHodle.hidden = true
                    
                    // 设置图像视图位置
                    self.setPostion(image)
            }
    }
}

    //设置占位图片的内容
    private func setPlaceHodle(image: UIImage?) {
    
        placeHodle.hidden = false
        
        placeHodle.image = image
        placeHodle.sizeToFit()
        placeHodle.center = scrollView.center
        
    
    
    }
    //重设scrollView的内容属性
    private func resetScrollView() {
        
            //图片属性
            imageView.transform = CGAffineTransformIdentity
        
        
            //scrollView内容属性
            scrollView.contentSize = CGSizeZero
            scrollView.contentInset = UIEdgeInsetsZero
            scrollView.contentOffset = CGPointZero
    
    }
    
    
    //设置imageView的位置
    private func setPostion(image: UIImage) {
    
        let size = self.displaySize(image)
        
        if size.height < scrollView.bounds.height {
        
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            let y = (scrollView.bounds.height - size.height) * 0.5
            
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
            
        }else {
        
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            //设置图片滚动的范围
            scrollView.contentSize = size
        }
    
    
    }
    
    //设置等比例缩放之后的宽度
    private func displaySize(image: UIImage) -> CGSize {
    
        let w = scrollView.bounds.width
        
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    
    }
    
    //返回中等尺寸的url
    private func bmiddleURL(url: NSURL) -> NSURL {
    
        var urlString = url.absoluteString
        
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: urlString)!
    
    }
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //更新UI
        setUpUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
    
        //添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(placeHodle)
        
        //设置布局
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        
        //设置代理
        scrollView.delegate = self
        
        //缩放的比例
        scrollView.maximumZoomScale = 2.0
        scrollView.minimumZoomScale = 0.5
        
        
        //添加手势
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    
    }
    
    //MARK: - 懒加载控件
     lazy var scrollView: UIScrollView = UIScrollView()
     lazy var imageView: UIImageView = UIImageView()
    
    //懒加载占位视图
    private lazy var placeHodle:ProgressImageView = ProgressImageView()

    
    
    
    
    
}


extension PhotoBrowserCell: UIScrollViewDelegate {

    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        //缩放imageView
        return imageView
        
    }

    //缩放结束后调用一次
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        // 关闭缩放图片
        if scale < 1 {
        
            photoDelegate?.photoBrowserCellDidTapImage()
            
            return
        
        }
        
        var offsetY = (scrollView.bounds.height - (view?.frame.height)!) * 0.5
        offsetY = offsetY < 0 ? 0 : offsetY
        
        var offsetX = (scrollView.bounds.width - (view?.frame.width)!) * 0.5
        offsetX = offsetX < 0 ? 0 : offsetX
        
        //设置间距
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
    }
    
    
    //是要缩放就会调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        
        //通知代理进行缩放笔记
        photoDelegate?.photoBrowserCellDidZoom(imageView.transform.a)
        
    }
    
}
